<template>
  <div class="jh-popover">
    <div class="content" v-if="visible" v-out-side-click="close" :style="{top:top+'px',left:left+'px',minWidth:minWidth+'px'}">
      <div class="triangle"></div>
      <slot></slot>
    </div>
    <div class="handler" @click.stop="toggleVisible()">
      <slot name="reference"></slot>
    </div>
  </div>
</template>

<script>
export default {
  model: {
    prop: 'value',
    event: 'change',
  },
  directives: {
    'out-side-click': {
      bind(el, binding) {
        el.__outsideClickEvent__ = e => {
          // 也可使用getBoundingClientRect检查
          if (!el.contains(e.target)) {
            binding.value(e);
          }
        };
        setTimeout(() => {
          document.body.addEventListener('click', el.__outsideClickEvent__);
        });
      },
      unbind(el) {
        document.body.removeEventListener('click', el.__outsideClickEvent__);
        delete el.__outsideClickEvent__;
      },
    },
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    offsetY: {
      type: Number,
      default: 10,
    },
  },
  data() {
    return {
      visible: false,
      top: 0,
      left: 0,
      minWidth: 0,
    };
  },
  mounted() {
    this.value ? this.show() : this.close();
  },
  methods: {
    show() {
      if (this.disabled) {
        return false;
      }
      this.top = this.$slots.reference[0].elm.offsetHeight + this.offsetY;
      this.minWidth = this.$slots.reference[0].elm.offsetWidth;
      this.visible = true;
    },
    close() {
      this.visible = false;
    },
    toggleVisible() {
      this.visible ? this.close() : this.show();
    },
  },
  watch: {
    visible() {
      this.$emit('change', this.visible);
    },
  },
};
</script>

<style lang="less" scoped>
.jh-popover {
  text-align: left;
  position: relative;
  & > .content {
    box-sizing: border-box;
    position: absolute;
    z-index: 999;
    min-width: 30px;
    min-height: 30px;
    padding: 5px;
    border: 1px solid #ebeef5;
    border-radius: 5px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    background: #fff;
    & > .triangle {
      position: absolute;
      top: -8px;
      left: 12px;
      width: 0;
      height: 0;
      border: 8px solid transparent;
      border-top: none;
      border-bottom-color: #ebeef5;
      &::after {
        content: '';
        position: absolute;
        display: block;
        width: 0;
        height: 0;
        left: -8px;
        top: 2px;
        border: 8px solid transparent;
        border-top: none;
        border-bottom-color: #fff;
      }
    }
  }
  & > .handler {
    display: inline-block;
    cursor: pointer;
  }
}
</style>


